# -*- coding: UTF-8 -*-
# @Time : 2021-01-30 11:07
# @File : StartAppium.py
# appium自动运行
import re
import socket
import subprocess
import time

from utils.LogUtil import my_log
import platform

log = my_log('Start_Appium')


def check_port(host="127.0.0.1", port="4723"):
    """
    检测端口号
    :param host:IP
    :param port:端口号
    :return:
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((host, int(port)))
        s.shutdown(2)
        log.info('port %s is used!' % port)
        return False
    except:
        log.info('port %s is not used!' % port)
        return True


def appium_start(host="127.0.0.1", port="4723", bpport="4724", uuid=None):
    """
    开启appium
    :param host:
    :param port:
    :param bpport:
    :param uuid:
    :return:
    """
    if check_port(host, port):
        cmd = 'appium -a %s -p %s -bp %s -U %s --session-override' % (host, port, bpport, uuid)
        # cmd = 'appium'
        appium_process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        while True:
            line = str(appium_process.stdout.readline().strip(), 'utf-8')
            log.info(line)
            if 'usage' in line or 'error' in line:
                log.error('启动失败，错误信息：{}'.format(appium_process.stderr.readline().strip(), 'utf-8'))
                break
            if 'listener started' in line:
                log.info('启动成功,参数是：host %s, port %s, bpport %s, uuid %s' % (host, port, bpport, uuid))
                break



def stop_server(port="4723"):
    """
    关闭appium
    :param port:
    :return:
    """
    if not check_port():
        # 判断系统，是windows或者mac,
        system_platform = platform.system()
        print(system_platform)
        if system_platform.lower() == 'windows':
            cmd = 'taskkill /f /im node.exe'
        else:
            cmd_lsof = 'lsof -l:{0}|grep{0}'.format(port)
            cmd = cmd_lsof + "|awk '{print $2}'|xarge kill -9"
        subprocess.call(cmd, shell=True, )
    else:
        log.info('端口未运行！')


def get_devices():
    cmd_adb = 'adb devices -l'
    devices_infe = subprocess.Popen(cmd_adb, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    # print(devices_infe.stdout.readlines())
    devices_list = list()
    for line in devices_infe.stdout.readlines():
        if 'model' in str(line, encoding='utf-8'):
            devices_list.append(str(line, encoding='utf-8'))
    # print(devices_list)
    get_devices_list = list()
    for info in devices_list:
        info = str(info)
        udid = re.search(r'(.*?)device', info).group(1).strip()
        get_devices_list.append(udid)
    log.info('获取的devices信息udid:%s' % get_devices_list)
    return get_devices_list


if __name__ == '__main__':
    # check_port()
    # appium_start()
    # stop_server()
    # get_devices()
    pass
